<?php
/**
 * Created by PhpStorm.
 * User: 跳梁
 * Date: 2016/10/19
 * Time: 11:11
 */
class messageSearchModule extends Module{

    /*
   * 在构造函数中装载所依赖的类或其他文件
  */
    function __construct()
    {
        $this->includePhp('messageSearch', 'messageSearch');
    }

    public function activate() {
        Module::importSQL (module_sql_path('messageSearch'));
    }
    public function run($message, $material, $status) {
        if($message->msgType==message_type_event){
            $userStatus = new stdClass();
            $userStatus->userName=$message->fromUserName;
            $userStatus->status=0;
            UserStatus::end($userStatus);
            return false;
        }
        $keys = trim($message->content);
        switch($status->status){
            case "0":
                if ($keys == '') {
                    return false;
                }
                return $this->sendList($message, $material, $status,$keys);
                break;
            case "1":
                if ($keys == '') {
                    return false;
                }
                return $this->sendBySerialNumber($message,$material,$status, $keys);
                break;
            case "2":
                return $this->getDirective($message,$material, $keys);
                break;
            case "3":
                return $this->delMessage($message,$material,$keys);
                break;
            case "4":
                return $this->addMessage($message,$material,$keys);
                break;
            case "5":
                return $this->addMaterialById($message,$material,$status);
                break;
            case "6":
                return $this->editMessage($message,$material,$keys);
                break;
        }
    }
    public function call($user, $method, $param){
        switch ($method) {
            case "uploadPermanent":
                self::uploadPermanent($param);
                break;
            case "uploadMaterial":
                self::uploadMaterial($param);
                break;
            case "getMaterialCount":
                self::getMaterialCount();
                break;
            case "searchMessage":
                $search = trim($param->search);
                $start = $param->start;
                $limit = $param->limit;
                messageSearch::searchMessage($search,$start,$limit);
                break;
            case "messageInfo":
                $id = $param->id;
                if(!$id){
                    Output::instance()->resultCode(code_lackof_param);
                    return;
                }
                messageSearch::messageInfo($id);
                break;
        }
    }
    //查找素材
    private function search($keyword,$page){
        $messageSearch = D("message_search");
        $where['deleted']=array("eq",0);
        $where['title']=array("like","%$keyword%");
        $start = $page*10;
        $limit = 10;
        $result['list'] = $messageSearch->where($where)->limit($start,$limit)->field("serialNumber,title")->select();
        if($result['list']){
            $result['count'] = $messageSearch->where($where)->count();
        }
        return $result;
    }
    //发送列表
    private function sendList($message,$material,$status,$keys,$page=0){
        $materialModel = D("material");
        if(!$material){
            $material = $materialModel->where("module='messageSearch' and type='config'")->find();
            if(!$material){
                $data['module']='messageSearch';
                $data['name']='messageSearchConfig';
                $data['type']='config';
                $data['xml']='<xml></xml>';
                $materialId = $materialModel->add($data);
                $material['id'] = $materialId;
            }
            $material = (object)$material;
        }
        $where['id']=array("eq",$material->id);
        $config = $materialModel->where($where)->getField("xml");
        if($config) {
            $xml = simplexml_load_string($config, 'SimpleXMLElement', LIBXML_NOCDATA);
            $content = $xml->message->item;
            $openWhileList = (String)$content->openWhileList;
            if($openWhileList){
                $power = $this->getPower($message->fromUserName,0);
                if(!$power){
                    $userStatus = new stdClass();
                    $userStatus->userName=$message->fromUserName;
                    $userStatus->status=0;
                    UserStatus::end($userStatus);
                    return false;
                }
            }
        }
        if(is_numeric($keys)){
            return $this->sendBySerialNumber($message,$material,$status,$keys);
        }
        $arr = $this->search($keys,$page);
        if(!$arr['count']){
            if($material->id){
                $userStatus = new stdClass();
                $userStatus->userName=$message->fromUserName;
                $userStatus->status=0;
                UserStatus::end($userStatus);
            }
            return false;
        }
        $str="查询'".$keys."'的结果:\n";
        foreach($arr['list'] as $key=>$value){
            $str.=$value['serialNumber']."  ".$value['title']."\n";
        }
        if($arr['count']>10*($page+1)){
            $str.="输入编号直接查看，输入n查看下一页";
        }else{
            $str.="输入编号直接查看";
        }
        $result = WeixinApi::sendServiceMsg($message->fromUserName,"text",$str);
        $result = json_decode($result,true);
        if($result['errcode']==0){
            $us = UserStatus::create($message->fromUserName, $material->id);
            $us->status = '1';
			$us->reserve1 = $page;
			$us->reserve2 = $keys;
            UserStatus::begin($us);
        }
        $result = new stdClass();
        $result->isModule=1;
        $result->content = $str;
        self::saveReplyMessage($message->fromUserName,message_type_text,$message->msgId,$result);
        return $result;
    }
    //判断指令
    private function getDirective($message,$material,$keys){
        $userName = $message->fromUserName;
        $power = $this->getPower($userName,1);
        if(!$power){
            return false;
        }
        $result = new stdClass();
        $result->isModule=1;
        $materialModel = D("material");
        $where['id']=array("eq",$material->id);
        $config = $materialModel->where($where)->getField("xml");
        if($config){
            $xml = simplexml_load_string($config,'SimpleXMLElement', LIBXML_NOCDATA);
            $content = $xml->message->item;
            $addStr=(String)$content->addStr;
            $editStr=(String)$content->editStr;
            $delStr=(String)$content->delStr;
            switch(trim($keys)){
                case $addStr:
                    $us = UserStatus::create($message->fromUserName, $material->id);
                    $us->status = '4';
                    UserStatus::update($us);
                    $str = "请输入标题：";
                    WeixinApi::sendServiceMsg($message->fromUserName,"text",$str);
                    $msg = new stdClass();
                    $msg->content = $str;
                    self::saveReplyMessage($message->fromUserName,message_type_text,$message->msgId,$msg);
                    return $result;
                    break;
                case $editStr:
                    $us = UserStatus::create($message->fromUserName, $material->id);
                    $us->status = '6';
                    UserStatus::update($us);
                    $str = "请输入要编辑的编号：";
                    WeixinApi::sendServiceMsg($message->fromUserName,"text",$str);
                    $msg = new stdClass();
                    $msg->content = $str;
                    self::saveReplyMessage($message->fromUserName,message_type_text,$message->msgId,$msg);
                    return $result;
                    break;
                case $delStr:
                    $us = UserStatus::create($message->fromUserName, $material->id);
                    $us->status = '3';
                    UserStatus::update($us);
                    $str = "请输入要删除的编号：";
                    WeixinApi::sendServiceMsg($message->fromUserName,"text",$str);
                    $msg = new stdClass();
                    $msg->content = $str;
                    self::saveReplyMessage($message->fromUserName,message_type_text,$message->msgId,$msg);
                    return $result;
                    break;
                default:
                    return false;
            }
        }else{
            return false;
        }
    }
    //添加素材
    private function addMaterialById($message,$material,$status){
        $MaterialModel = D("material");
        $id = $status->reserve1;
        $title = $status->reserve2;
        $result = new stdClass();
        $result->isModule=1;
        $result->module="messageSearch";
        $result->method="uploadMaterial";
        $tempResult=new stdClass();
        $tempResult->list = array();
        switch ($message->msgType) {
            case message_type_text:
                $keys = trim($message->content);
                if($keys=="ov"){
                    $userStatus = new stdClass();
                    $userStatus->userName=$message->fromUserName;
                    $userStatus->status=0;
                    UserStatus::end($userStatus);
                    $str="素材添加完成！";
                    WeixinApi::sendServiceMsg($message->fromUserName,"text",$str);
                    $result->content = $str;
                    self::saveReplyMessage($message->fromUserName,message_type_text,$message->msgId,$result);
                    break;
                }
                $keys = base64_encode($keys);
                $result->ispost = 1;
                $params['title']=$title;
                $params['type']=message_type_text;
                $params['id']=$id;
                $params['content']=$keys;
                array_push($tempResult->list,$params);
                break;
            case message_type_image:
                $result->ispost = 1;
                $params['title']=$title;
                $params['type']=message_type_image;
                $params['id']=$id;
                $params['mediaId']=(string)$message->mediaId;
                array_push($tempResult->list,$params);
                break;
            case message_type_voice:
                $result->ispost = 1;
                $params['title']=$title;
                $params['type']=message_type_voice;
                $params['id']=$id;
                $params['mediaId']=(string)$message->mediaId;
                array_push($tempResult->list,$params);
                break;
            case message_type_video:
                $result->ispost=1;
                $params['title']=$title;
                $params['type']=message_type_video;
                $params['id']=$id;
                $params['mediaId']=(string)$message->mediaId;
                array_push($tempResult->list,$params);
                break;
            case message_type_shortvideo:
                $result->ispost=1;
                $params['title']=$title;
                $params['type']=message_type_video;
                $params['id']=$id;
                $params['mediaId']=(string)$message->mediaId;
                array_push($tempResult->list,$params);
                break;
        }
        $result->params = $tempResult;
        return $result;
    }
    //下载素材并上传到OSS
    public function uploadMaterial($param){
        $MaterialModel = D("material");
        $list = $param->list;
        foreach($list as $key=>$value){
            $type = $value->type;
            $id = $value->id;
            $title = $value->title;
            $data['module']="messageSearch";
            $data['moduleId']="$id";
            $data['name']=$title;
            $data['updateTime']=date("Y-m-d H:i:s");
            switch($type){
                case message_type_image:
                    $mediaId = $value->mediaId;
                    $fileName = md5($mediaId).".jpg";
                    $result = R("Upload/uploadMediaToOss",array($mediaId,$fileName,$type));
                    $path = $result->path;
                    $data['type']='image';
                    $data['xml']="<xml><message><item><imageUrl><![CDATA[$path]]></imageUrl></item></message></xml>";
                    break;
                case message_type_voice:
                    $mediaId = $value->mediaId;
                    $fileName = md5($mediaId).".amr";
                    $result = R("Upload/uploadMediaToOss",array($mediaId,$fileName,"audio"));
                    $path = $result->path;
                    $data['type']='audio';
                    $data['xml']="<xml><message><item><audioUrl><![CDATA[$path]]></audioUrl></item></message></xml>";
                    break;
                case message_type_video:
                    $mediaId = $value->mediaId;
                    $fileName = md5($mediaId).".mp4";
                    $result = R("Upload/uploadMediaToOss",array($mediaId,$fileName,"video"));
                    $path = $result->path;
                    $data['type']='video';
                    $data['xml']="<xml><message><item><videoUrl><![CDATA[$path]]></videoUrl></item></message></xml>";
                    break;
                case message_type_text:
                    $keys = $value->content;
                    $data['type']='text';
                    $data['xml']="<xml><message><item><content><![CDATA[$keys]]></content></item></message></xml>";
                    break;
            }
            $MaterialModel->add($data);
        }
    }
    //管理人员添加消息
    private function addMessage($message,$material,$keys){
        $result = new stdClass();
        $result->isModule=1;
        if($message->msgType!=message_type_text){
            $str = "消息类型错误！";
            WeixinApi::sendServiceMsg($message->fromUserName,"text",$str);
            $msg = new stdClass();
            $msg->content = $str;
            self::saveReplyMessage($message->fromUserName,message_type_text,$message->msgId,$msg);
            return $result;
        }
        $messageSearch = M("message_search");
        $serialNumber = $messageSearch->getField("max(serialNumber)");
        if(!$serialNumber){
            $serialNumber=1000;
        }else{
            $serialNumber=++$serialNumber;
        }
        $time = date("Y-m-d H:i:s");
        $searchData['title']=$keys;
        $searchData['serialNumber']=$serialNumber;
        $searchData['updateTime']=$time;
        $searchData['createTime']=$time;
        $id = $messageSearch->add($searchData);
        $this->addMessageLog($message->fromUserName,$id);
        $us = UserStatus::create($message->fromUserName, $material->id);
        $us->status = '5';
        $us->reserve1=$id;
        $us->reserve2=$keys;
        UserStatus::update($us);
        $str = "编号".$serialNumber."请上传素材，输入ov结束";
        WeixinApi::sendServiceMsg($message->fromUserName,"text",$str);
        $msg = new stdClass();
        $msg->content = $str;
        self::saveReplyMessage($message->fromUserName,message_type_text,$message->msgId,$msg);
        return $result;
    }
    //编辑消息素材
    private function editMessage($message,$material,$keys){
        $messageSearch = M("message_search");
        $messageInfo = $messageSearch->where("serialNumber='$keys' and deleted=0")->find();
        if(!$messageInfo){
            $str = "编号不存在！";
            $us = UserStatus::create($message->fromUserName, $material->id);
            $us->status = '0';
            UserStatus::end($us);
        }else{
            $str = "编号".$keys."请上传素材，输入ov结束";
            $this->addMessageLog($message->fromUserName,$messageInfo['id']);
            $us = UserStatus::create($message->fromUserName, $material->id);
            $us->status = '5';
            $us->reserve1 = $messageInfo['id'];
            $us->reserve2 = $messageInfo['title'];
            UserStatus::update($us);
        }
        WeixinApi::sendServiceMsg($message->fromUserName,"text",$str);
        $msg = new stdClass();
        $msg->content = $str;
        self::saveReplyMessage($message->fromUserName,message_type_text,$message->msgId,$msg);
        $result = new stdClass();
        $result->isModule=1;
        return $result;
    }
    //管理人员删除消息
    private function delMessage($message,$material,$keys){
        $messageSearch = M("message_search");
        $messageInfo = $messageSearch->where("serialNumber='$keys' and deleted=0")->find();
        if(!$messageInfo){
            $str = "编号不存在！";
            $us = UserStatus::create($message->fromUserName, $material->id);
            $us->status = '0';
            UserStatus::end($us);
        }else{
            $delResult = $this->delMessageById($messageInfo['id']);
            $delResult?$str = "删除成功！":$str = "删除失败！";
        }
        $this->addMessageLog($message->fromUserName,$messageInfo['id']);
        $us = UserStatus::create($message->fromUserName, $material->id);
        $us->status = '0';
        UserStatus::end($us);
        WeixinApi::sendServiceMsg($message->fromUserName,"text",$str);
        $msg = new stdClass();
        $msg->content = $str;
        self::saveReplyMessage($message->fromUserName,message_type_text,$message->msgId,$msg);
        $result = new stdClass();
        $result->isModule=1;
        return $result;
    }
    //通过ID删除消息
    public function delMessageById($id){
        $messageSearch = D("message_search");
        $material = D("material");
        $data['deleted']=1;
        $data['updateTime']=date("Y-m-d H:i:s");
        $result = $messageSearch->where("id=$id")->save($data);
        if($result!==false){
            $where['module']=array("eq","messageSearch");
            $where['moduleId']=array("eq",$id);
            $where['deleted']=array("eq",0);
            $materialList = $material->where($where)->select();
            foreach($materialList as $key=>$value){
                if($value['media_id']){
                    $mdata=null;
                    $mdata['deleted']=1;
                    $mdata['updateTime']=date("Y-m-d H:i:s");
                    $result = WeixinApi::del_material($value['media_id']);
                    $result = json_decode($result,true);
                    if($result['errcode']==0){
                        $mdata['media_id']=null;
                    }else{
                        Log::write("删除永久素材失败 ".$result['errmsg']);
                    }
                    $material->where("id=".$value['id'])->save($mdata);
                }
            }
            return true;
        }
        return false;
    }
    //记录操作记录
    private function addMessageLog($userName,$id){
        $userInfo = M("user_weixin_info");
        $messageLog = M("message_log");
        $userId = $userInfo->where("openid='$userName'")->getField("id");
        $data['userId']=$userId;
        $data['module']='messageSearch';
        $data['moduleId']=$id;
        $data['createTime']=date("Y-m-d H:i:s");
        $messageLog->add($data);
    }
    //判断管理权限
    private function getPower($userName,$admin){
        $messageAdmin = D("message_admin");
        $where['openid']=array("eq",$userName);
        $where['deleted']=array("eq",0);
        $admin?$where['admin']=array("eq",$admin):"";
        $result = $messageAdmin->where($where)->find();
        if(!$result){
            return false;
        }
        return true;
    }
    //输入编号 或者下一页
    private function sendBySerialNumber($message,$material,$status,$keys){
        $cid = Session::$user['customerId'];
        $result = new stdClass();
        $result->isModule=1;
        $result->module="messageSearch";
        $result->method="uploadPermanent";
        $tempResult=new stdClass();
        $tempResult->list = array();
        if($keys=="n"){
            $page = $status->reserve1;
			$keys = $status->reserve2;
            $this->sendList($message,$material,$status,$keys,++$page);
        }else{
            if(is_numeric($keys)){
                $messageSearch = D("message_search");
                $materialModule = D('material');
                $where['serialNumber']=array("eq",$keys);
                $where['deleted']=array("eq",0);
                $searchResult = $messageSearch->where($where)->find();
                if(!$searchResult&&!$status->status){
                    return false;
                }
                if(!$searchResult){
                    $str = "编号不存在！";
                    $userStatus = new stdClass();
                    $userStatus->userName = $message->fromUserName;
                    $userStatus->status = 0;
                    UserStatus::end($userStatus);
                    $rm = $message->reply(message_type_text);
                    $rm->content = $str;
                    return $rm;
                }
                $arr = $materialModule->where("module='messageSearch' and deleted=0 and moduleId=".$searchResult['id'])->select();
                if(!$arr) {
                    $str = "编号".$keys."没有任何内容！";
                    WeixinApi::sendServiceMsg($message->fromUserName,"text",$str);
                    $msg = new stdClass();
                    $msg->content = $str;
                    self::saveReplyMessage($message->fromUserName,message_type_text,$message->msgId,$msg);
                }else{
                    $str = "查询编号".$keys."的内容：";
                    WeixinApi::sendServiceMsg($message->fromUserName,"text",$str);
                    $msg = new stdClass();
                    $msg->content = $str;
                    self::saveReplyMessage($message->fromUserName,message_type_text,$message->msgId,$msg);
                    foreach($arr as $key=>$value){
                        $materilId = $value['id'];
                        $xml = simplexml_load_string($value['xml'],'SimpleXMLElement', LIBXML_NOCDATA);
                        $content = $xml->message->item;
                        switch($value['type']){
                            case "text":
                                $str = (String)$content->content;
                                if($str == base64_encode(base64_decode($str))){
                                    $str = base64_decode($str);
                                }
                                WeixinApi::sendServiceMsg($message->fromUserName,"text",$str);
                                $msg = new stdClass();
                                $msg->content = $str;
                                self::saveReplyMessage($message->fromUserName,message_type_text,$message->msgId,$msg);
                                break;
                            case "music":
                                if($value['media_id']){
                                    WeixinApi::sendServiceMsg($message->fromUserName,"music",(String)$content->musicUrl,null,$value['media_id']);
                                    $msg = new stdClass();
                                    $msg->url = (String)$content->musicUrl;
                                    self::saveReplyMessage($message->fromUserName,message_type_music,$message->msgId,$msg);
                                }else {
                                    $result->ispost = "1";
                                    $params['content']=(String)$content->musicUrl;
                                    $params['musicImgUrl']=(String)$content->imgUrl;
                                    $params['type']=$value['type'];
                                    $params['id']=$value['id'];
                                    $params['userName']=$message->fromUserName;
                                    $params['msgId']=$message->msgId;
                                    array_push($tempResult->list,$params);
                                }
                                break;
                            case "image":
                                if($value['media_id']){
                                    WeixinApi::sendServiceMsg($message->fromUserName,"image",null,null,$value['media_id']);
                                    $msg = new stdClass();
                                    $msg->url = (String)$content->imageUrl;
                                    $msg->mediaId = $value['media_id'];
                                    self::saveReplyMessage($message->fromUserName,message_type_image,$message->msgId,$msg);
                                }else{
                                    $result->ispost = "1";
                                    $params['content']=(String)$content->imageUrl;
                                    $params['type']=$value['type'];
                                    $params['id']=$value['id'];
                                    $params['userName']=$message->fromUserName;
                                    $params['msgId']=$message->msgId;
                                    array_push($tempResult->list,$params);
                                }
                                break;
                            case "audio":
                                if($value['media_id']){
                                    WeixinApi::sendServiceMsg($message->fromUserName,"voice",null,null,$value['media_id']); $msg = new stdClass();
                                    $msg = new stdClass();
                                    $msg->url = (String)$content->audioUrl;
                                    $msg->mediaId = $value['media_id'];
                                    self::saveReplyMessage($message->fromUserName,message_type_voice,$message->msgId,$msg);
                                }else {
                                    $result->ispost = "1";
                                    $params['content']=(String)$content->audioUrl;
                                    $params['type']=$value['type'];
                                    $params['id']=$value['id'];
                                    $params['userName']=$message->fromUserName;
                                    $params['msgId']=$message->msgId;
                                    array_push($tempResult->list,$params);
                                }
                                break;
                            case "video":
                                if($value['media_id']){
                                    WeixinApi::sendServiceMsg($message->fromUserName,"video",null,null,$value['media_id']);
                                    $msg = new stdClass();
                                    $msg->url = (String)$content->videoUrl;
                                    $msg->mediaId = $value['media_id'];
                                    self::saveReplyMessage($message->fromUserName,message_type_video,$message->msgId,$msg);
                                }else {
                                    $result->ispost = "1";
                                    $params['content']=(String)$content->videoUrl;
                                    $params['type']=$value['type'];
                                    $params['id']=$value['id'];
                                    $params['title']=$searchResult['title'];
                                    $params['userName']=$message->fromUserName;
                                    $params['msgId']=$message->msgId;
                                    array_push($tempResult->list,$params);
                                }
                                break;
                            case "news":
                                $id= (String)$content->newsId;
                                $news = $materialModule->where("id=$id")->find();
                                $xml = simplexml_load_string($news['xml'],'SimpleXMLElement', LIBXML_NOCDATA);
                                $item = $xml->Articles->item;
                                $articles=array();
                                foreach($item as $key=>$value){
                                    $article=new stdClass();
                                    $article->title = urlencode((string)$value->title);
                                    $article->url = urlencode((string)$value->url);
                                    $article->picurl = urlencode((string)$value->picUrl);
                                    $article->description = urlencode((string)$value->description);
                                    array_push($articles, $article);
                                }
                                $toUser = $message->fromUserName;
                                WeixinApi::sendServiceMsg($toUser, 'news','',$articles);
                                $msg = new stdClass();
                                $msg->articles = $articles;
                                self::saveReplyMessage($message->fromUserName,message_type_news,$message->msgId,$msg);
                                break;
                            case "product":
                                $id= (String)$content->materialId;
                                $url = C("SERVER_HOST") . "call.html?customerId=".$cid."&module=product&method=getProduct&params=".urlencode(json_encode(array("id"=>$id)));
                                $proInfo = M("")->table("wx_module_product")->where("id=$id")->find();
                                $articles=array();
                                $article=new stdClass();
                                $article->title = urlencode($proInfo['name']);
                                $article->url = urlencode($url);
                                $article->picurl = urlencode($proInfo['picUrl']);
                                $article->description = urlencode($proInfo['description']);
                                array_push($articles, $article);
                                $toUser = $message->fromUserName;
                                WeixinApi::sendServiceMsg($toUser, 'news','',$articles);
                                $msg = new stdClass();
                                $msg->articles = $articles;
                                self::saveReplyMessage($message->fromUserName,message_type_news,$message->msgId,$msg);
                                break;
                            case "content":
                                $id= (String)$content->materialId;
                                $url = C("SERVER_HOST") . "call.html?customerId=".$cid."&module=micontent&method=getMiContentDetail&params=".urlencode(json_encode(array("id"=>$id)));
                                $contentInfo = M("")->table("wx_micontent")->where("id=$id")->find();
                                $articles=array();
                                $article=new stdClass();
                                $article->title = urlencode($contentInfo['title']);
                                $article->url = urlencode($url);
                                $article->picurl = urlencode($contentInfo['picUrl']);
                                $article->description = urlencode($contentInfo['description']);
                                array_push($articles, $article);
                                $toUser = $message->fromUserName;
                                WeixinApi::sendServiceMsg($toUser, 'news','',$articles);
                                $msg = new stdClass();
                                $msg->articles = $articles;
                                self::saveReplyMessage($message->fromUserName,message_type_news,$message->msgId,$msg);
                                break;
                        }
                        $materialModule->where("id=".$materilId)->setInc("readCount");
                    }
                    $userStatus = new stdClass();
                    $userStatus->userName=$message->fromUserName;
                    $userStatus->status=0;
                    UserStatus::end($userStatus);
                }
            }else{
                return $this->sendList($message, $material,$status, $keys);
            }
        }
       $result->params = $tempResult;
       return $result;
    }
    //保存记录
    private function saveReplyMessage($toUserName,$msgType,$msgId,$msg) {
        $cid = Session::$user['customerId'];
        $Message = D("Message");
        $Message->create();
        $Message->fromUserName = "";
        $Message->toUserName = $toUserName;
        $Message->msgType = $msgType;
        $Message->msgId = $msgId;
        $Message->customerId = $cid;
        $Message->createTime = date('Y-m-d H:i:s');
        $Message->msgMark = message_type_reply;

        switch ($msgType) {
            case message_type_text:
                $Message->content = trim($msg->content);
                $result = $Message->add();
                if (!$result) {
                    Log::write('Add Message Error:' . $Message->getError());
                }
                break;
            case message_type_music:
                $Message->url = trim($msg->url);
                $result = $Message->add();
                if (!$result) {
                    Log::write('Add Message Error:' . $Message->getError());
                }
                break;
            case message_type_video:
                $Message->url = trim($msg->url);
                $Message->mediaId = trim($msg->mediaId);
                $result = $Message->add();
                if (!$result) {
                    Log::write('Add Message Error:' . $Message->getError());
                }
                break;
            case message_type_voice:
                $Message->url = trim($msg->url);
                $Message->mediaId = trim($msg->mediaId);
                $result = $Message->add();
                if (!$result) {
                    Log::write('Add Message Error:' . $Message->getError());
                }
                break;
            case message_type_image:
                $Message->url = trim($msg->url);
                $Message->mediaId = trim($msg->mediaId);
                $result = $Message->add();
                if (!$result) {
                    Log::write('Add Message Error:' . $Message->getError());
                }
                break;
            case message_type_news:
                $Message->content=json_decode($msg->articles);
                $result = $Message->add();
                if (!$result) {
                    Log::write('Add News Message Error:' . $Message->getError());
                }
                break;
            default:
                // 记录日志
        }
    }
    public function getMaterialCount(){
        $materialModel = D("material");
        $materialCount = WeixinApi::get_materialcount();
        $materialCount = json_encode($materialCount,true);
        $image_count = $materialCount['image_count']+$materialCount['news_count'];
        $other_count = $materialCount['voice_count']+$materialCount['video_count'];
        if($image_count>=5000){
            $materialInfo = $materialModel->where("deleted=0 and media_id is not null and (module='news' or type='image' or type='music')")
                ->order("readCount asc")->field("id,media_id")->find();
            $delResult = WeixinApi::del_material($materialInfo['media_id']);
            $delResult = json_decode($delResult,true);
            $materialModel->where("id=".$materialInfo['id'])->setField("media_id",null);
            if($delResult['errcode']!=0){
                Log::write("删除失败  ".$delResult['errmsg']);
                self::getMaterialCount();
            }
        }
        if($other_count>=1000){
            $materialInfo = $materialModel->where("deleted=0 and media_id is not null and (type='audio' or type='video')")
                ->order("readCount asc")->field("id,media_id")->find();
            $delResult = WeixinApi::del_material($materialInfo['media_id']);
            $delResult = json_decode($delResult,true);
            $materialModel->where("id=".$materialInfo['id'])->setField("media_id",null);
            if($delResult['errcode']!=0){
                Log::write("删除失败  ".$delResult['errmsg']);
                self::getMaterialCount();
            }
        }
        return true;
    }
    private function uploadPermanent($param){
        $materialModel = D("material");
        $list = $param->list;
        foreach($list as $key=>$value){
            self::getMaterialCount();
            $content = $value->content;
            $type = $value->type;
            $id = $value->id;
            $toUser = $value->userName;
            $musicImgUrl = $value->musicImgUrl;
            $msgId = $value->msgId;
            switch($type){
                case "image":
                    $result = self::saveFile($content,$type);
                    $file_info=array(
                        'filename'=>$result['path'], //国片相对于网站根目录的路径
                        'content-type'=>$result['content-type'], //文件类型
                        'filelength'=>$result['size'] //图文大小
                    );
                    $path = $result['path'];
                    $result = WeixinApi::add_material("image",$file_info);
                    @unlink($path);
                    $result = json_decode($result,true);
                    $materialModel->where("id=$id")->setField("media_id",$result['media_id']);
                    //发送客服消息
                    WeixinApi::sendServiceMsg($toUser,"image",null,null,$result['media_id']);
                    $msg = new stdClass();
                    $msg->url = $content;
                    $msg->mediaId = $result['media_id'];
                    self::saveReplyMessage($toUser,message_type_image,$msgId,$msg);
                    break;
                case "video":
                    $title = $materialModel->where("id=$id")->getField("name");
                    $result = self::saveFile($content,$type);
                    $file_info=array(
                        "filename"=>$result['path'],
                        "title"=>urlencode($title),
                        "introduction"=>urlencode($title)
                    );
                    $path = $result['path'];
                    $result = WeixinApi::add_material("video",$file_info);
                    @unlink($path);
                    $result = json_decode($result,true);
                    $materialModel->where("id=$id")->setField("media_id",$result['media_id']);
                    //发送客服消息
                    WeixinApi::sendServiceMsg($toUser,"video",null,null,$result['media_id']);
                    $msg = new stdClass();
                    $msg->url = $content;
                    $msg->mediaId = $result['media_id'];
                    self::saveReplyMessage($toUser,message_type_video,$msgId,$msg);
                    break;
                case "audio":
                    $result = self::saveFile($content,$type);
                    $file_info=array(
                        'filename'=>$result['path'], //国片相对于网站根目录的路径
                        'content-type'=>$result['content-type'], //文件类型
                        'filelength'=>$result['size'] //图文大小
                    );
                    $path = $result['path'];
                    $result = WeixinApi::add_material("voice",$file_info);
                    @unlink($path);
                    $result = json_decode($result,true);
                    $materialModel->where("id=$id")->setField("media_id",$result['media_id']);
                    sleep(1);
                    WeixinApi::sendServiceMsg($toUser,"voice",null,null,$result['media_id']);
                    $msg = new stdClass();
                    $msg->url = $content;
                    $msg->mediaId = $result['media_id'];
                    self::saveReplyMessage($toUser,message_type_voice,$msgId,$msg);
                    break;
                case "music":
                    $result = self::saveFile($musicImgUrl,"image");
                    $file_info=array(
                        'filename'=>$result['path'], //国片相对于网站根目录的路径
                        'content-type'=>$result['content-type'], //文件类型
                        'filelength'=>$result['size'] //图文大小
                    );
                    $path = $result['path'];
                    $result = WeixinApi::add_material("image",$file_info);
                    @unlink($path);
                    $result = json_decode($result,true);
                    $materialModel->where("id=$id")->setField("media_id",$result['media_id']);
                    WeixinApi::sendServiceMsg($toUser,"music",$content,null,$result['media_id']);
                    $msg = new stdClass();
                    $msg->url = $content;
                    self::saveReplyMessage($toUser,message_type_music,$msgId,$msg);
            }
        }
    }
    //下载资源到本地
    public function saveFile($path,$type) {
        $fileName = pathinfo($path);
        $image_name = strToLower($fileName['basename']);
        $ch = curl_init ($path);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
        $img = curl_exec ($ch);
        curl_close ($ch);
        $fp = fopen($image_name,'w');
        fwrite($fp, $img);
        fclose($fp);
        if($type=='image'&&filesize($image_name)>=2048000){
            self::resizejpg($image_name,2000,$image_name);
        }
        $result['size'] = filesize($image_name);
        $result['path']=$image_name;
        $result['content-type']=$type."/".$fileName['extension'];
        return $result;
    }
    //图片压缩
    function resizejpg($imgsrc,$undersize,$savepath)
    {						//输出格式
        $arr = getimagesize($imgsrc);    						//获取源文件的长宽信息
        $size = filesize($imgsrc);
        $size = ceil($size/1024);       						//计算源文件的大小(kb)
        $percentum = $undersize / $size; 						//变成原来的多少
        if($size <= $undersize){								//已经满足的照片则不予处理
            return ;
        }
        $dest_area = $arr[0]*$arr[1]*$percentum;          		//转换之后的面积
        $newpercent = sqrt($dest_area/($arr[0]*$arr[1])); 		//长宽变化的比率
        $imgWidth = $arr[0]*$newpercent; 			       		//计算出来的宽缩放后的宽度
        $imgHeight = $arr[1]*$newpercent; 				  		//计算出来的高缩放后的高度

        // Create image and define colors
        $imgsrc = imagecreatefromjpeg($imgsrc);
        $image = imagecreatetruecolor($imgWidth, $imgHeight);   //创建一个彩色的底图
        imagecopyresampled($image, $imgsrc, 0, 0, 0, 0,$imgWidth,$imgHeight,$arr[0], $arr[1]);
        imagejpeg($image,$savepath);        				    //保存jpg格式图片
        imagedestroy($image);
    }
}
$module = new messageSearchModule();
Module::addModule($module);